package cn.itsource.pethome.web.controller;

import cn.itsource.pethome.domain.Employee;
import cn.itsource.pethome.domain.Product;
import cn.itsource.pethome.query.ProductQuery;
import cn.itsource.pethome.service.IProductService;
import cn.itsource.pethome.utils.AjaxResult;
import cn.itsource.pethome.utils.RedisUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class ProductController {

    @Autowired
    private IProductService productService;

    /**
     * 分页查询商品数据
     * @param productQuery
     * @return
     */
    @PatchMapping("/product")
    public PageInfo<Product> page(@RequestBody ProductQuery productQuery){
        return productService.findPage(productQuery);
    }

    /**
     * 新增或者编辑
     * @param product
     * @return
     */
    @PutMapping("/product")
    public AjaxResult save(@RequestBody Product product, HttpServletRequest request){
        try {
            if(product.getId() == null){
                //获取后台系统登录用户
                Employee employee = RedisUtils.INSTANCE.getUser(request, Employee.class);
                product.setShop_id(employee.getShop_id());
            }
            productService.save(product);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("商品保存失败！" + e.getMessage());
        }
    }


}
